﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Xml.Serialization;

namespace SysMisc
{
    public class Serialization
    {
        //序列化到Xml文件
        public static void SerializeToXml<T>(T o, string filePath)
        {
            try
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                StreamWriter sw = new StreamWriter(filePath, false);
                formatter.Serialize(sw, o);
                sw.Flush();
                sw.Close();
            }
            catch (Exception e) { LogHelper.Error(typeof(Serialization), e); }
        }

        //从Xml文件反序列化
        public static T DeSerializeFromXml<T>(string filePath)
        {
            StreamReader sr = null;
            try
            {
                XmlSerializer formatter = new XmlSerializer(typeof(T));
                sr = new StreamReader(filePath);
                T o = (T)formatter.Deserialize(sr);
                sr.Close();
                return o;
            }
            catch (Exception e)
            {
                if( null != sr )
                    sr.Close();
                LogHelper.Error(typeof(Serialization), e);
            }
            return default(T);
        }

        public static void SerializeToBinary<T>(T o, string filePath)
        {
            try
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, o);
                fs.Close();
            }
            catch (Exception e) { LogHelper.Error(typeof(Serialization), e); }
        }

        public static T DeSearializeFromBinary<T>(string filePath)
        {
            FileStream fs = null;
            try
            {
                fs = new FileStream(filePath, FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                T o = (T)bf.Deserialize(fs);
                fs.Close();
                return o;
            }
            catch (Exception e) {
                if (null != fs)
                    fs.Close();
                LogHelper.Error(typeof(Serialization), e);
            }

            return default(T);
        }
    }
}
